﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetMVC.Common;
using DotNetMVC.DTO;
using DotNetMVC.IService;
using DotNetMVC.Model;
using DotNetMVC.Website.Areas.WebAdmin.Filters;
using DotNetMVC.Website.Areas.WebAdmin.Models;
using DotNetMVC.Website.Areas.WebAdmin.Common;

namespace DotNetMVC.Website.Areas.WebAdmin.Controllers
{
    public class AdminUserController : Controller
    {
        public IAdminUserService adminUserService { get; set; }
        public IAdminUserRoleService adminUserRoleService { get; set; }
        public IRoleService roleService { get; set; }
        public IAdminUserPermissionService adminUserPermissionService { get; set; }
        public IPermissionService permissionService { get; set; }

        [AdminAuthorize(IsCheck = true)]
        public ActionResult List(AdminUserSearchOptions options, int pageIndex = 1)
        {
            long total;
            int pageSize = 10, maxPagerCount = 10;
            AdminUserDTO[] list = adminUserService.GetPagedData(options, out total, pageIndex, pageSize);
            ViewBag.totalCount = total;
            ViewBag.pageIndex = pageIndex;
            ViewBag.pageSize = pageSize;
            ViewBag.maxPagerCount = maxPagerCount;
            return View(list);
        }

        [HttpGet]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Add()
        {
            //获取所有角色
            var roles = roleService.GetRoles();
            ViewBag.Roles = roles;
            return View();
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Add(AdminUserAddViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = MVCHelper.GetValidMsg(ModelState)
                });
            }

            //验证用户名是否存在
            if (adminUserService.Exist(model.name))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "用户名已存在，请更换" });
            }


            //城市
            long? cityId = model.cityId <= 0 ? null : model.cityId;

            //新增管理员
            long userId = adminUserService.Add(model.name, model.password, model.phoneNum, model.email);
            //新增角色
            adminUserRoleService.AddRoleIds(userId, model.adminRoles);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "新增管理员"+ model.name +"（Id:"+ userId + "）");

            return Json(new AjaxResult { Status = "ok" });
            //return View();
        }

        [HttpGet]
        public string Exist(string name)
        {
            //remote:远程地址只能输出 "true" 或 "false"，不能有其他输出。
            //存在： "false"
            return adminUserService.Exist(name) ? "false" : "true";
        }

        [HttpGet]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Edit(long id)
        {
            AdminUserDTO user = adminUserService.GetDTOById(id);
            if (user == null)
            {
                return View("Error", (object)"获取不到管理员信息");
            }
            RoleDTO[] adminRoles = roleService.GetAdminRoles(user.Id);
            RoleDTO[] allRoles = roleService.GetRoles();

            AdminUserEditGetViewModel model = new AdminUserEditGetViewModel();
            model.User = user;
            model.AllRoles = allRoles;
            return View(model);
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Edit(AdminUserEditViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = MVCHelper.GetValidMsg(ModelState)
                });
            }

            var user = adminUserService.GetById(model.Id);
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "管理员信息不存在" });
            }

            //城市
            long? cityId = model.cityId <= 0 ? null : model.cityId;

            //更新管理员
            adminUserService.Update(model.Id, model.password, model.phoneNum, model.email);
            //更新角色
            adminUserRoleService.UpdateRoleIds(user.Id, model.adminRoles);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "修改管理员" + user.Name + "（Id:" + user.Id + "）");

            return Json(new AjaxResult { Status = "ok" });
        }


        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Delete(long id)
        {
            AdminUserDTO user = adminUserService.GetDTOById(id);
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到管理员信息" });
            }
            adminUserService.MarkDeleted(id);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "删除管理员" + user.Name + "（Id:" + user.Id + "）");

            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult BatchDelete(long[] selectdIds)
        {
            if (selectdIds.Length <= 0)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "未选中删除数据" });
            }

            List<long> list = new List<long>();
            foreach (long id in selectdIds)
            {
                list.Add(id);
            }

            adminUserService.BatchMarkDeleted(list);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "批量删除管理员（Ids:" + string.Join(",",list) + "）");

            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult EnableAdminUser(long id)
        {
            AdminUserDTO user = adminUserService.GetDTOById(id);
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到管理员信息" });
            }
            adminUserService.ChangStatus(id, true);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "启用管理员" + user.Name + "（Id:" + user.Id + "）");

            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult DisableAdminUser(long id)
        {
            AdminUserDTO user = adminUserService.GetDTOById(id);
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error",ErrorMsg= "获取不到管理员信息" });
            }
            adminUserService.ChangStatus(id, false);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "禁用管理员" + user.Name + "（Id:" + user.Id + "）");

            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpGet]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult SetPermission(long id)
        {
            AdminUserSetPermissionGetViewModel vierModel = new AdminUserSetPermissionGetViewModel();
            AdminUserDTO user = adminUserService.GetDTOById(id);
            if (user == null)
            {
                return View("Error", (object)"获取不到管理员信息");
            }
            vierModel.User = user;
            vierModel.Permissions = permissionService.GetPermissionsByLevel();
            vierModel.HasPermissions = adminUserPermissionService.GetHasPermissions(user.Id);
            return View(vierModel);
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult SetPermission(long adminId, long permissionId, int flg)
        {
            AdminUserDTO user = adminUserService.GetDTOById(adminId);
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到管理员信息" });
            }

            PermissionDTO permission = permissionService.GetDTOById(permissionId);
            if (permission == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到权限信息" });
            }

            bool hasPermission = flg == 1 ? true : false;
            if (adminUserPermissionService.GetSingle(adminId, permissionId) == null)
            {
                //新增管理员权限关系
                adminUserPermissionService.Add(adminId, permissionId, hasPermission);
            }
            else
            {
                //修改管理员权限关系
                adminUserPermissionService.Update(adminId, permissionId, hasPermission);
            }

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "设置管理员" + user.Name + "（Id:" + user.Id + "）"+(flg == 1?"拥有":"拒绝") +"特殊权限（"+ permission.Name + "）");

            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult SetPermissionDel(long adminId, long permissionId)
        {
            AdminUserDTO user = adminUserService.GetDTOById(adminId);
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到管理员信息" });
            }

            PermissionDTO permission = permissionService.GetDTOById(permissionId);
            if (permission == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到权限信息" });
            }

            if (adminUserPermissionService.GetSingle(adminId, permissionId) == null)
            {
                return Json(new AjaxResult { Status = "error",ErrorMsg="获取不到管理员和权限关系"});
            }
            //删除管理员权限关系
            adminUserPermissionService.Deleted(adminId,permissionId);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "删除管理员" + user.Name + "（Id:" + user.Id + "）" + "特殊权限（" + permission.Name + "）");
            return Json(new AjaxResult { Status = "ok" });
        }
    }
}